<!--
  分账记录列表组件
  @description 查看分账规则的执行记录
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1200px" :scroll="true" max-height="600px">
    <div v-loading="loading">
      <!-- 规则信息展示 -->
      <el-descriptions :column="3" border class="mb-20px" v-if="splitRuleData">
        <el-descriptions-item :label="t('settle.splitRule.ruleName')">
          {{ splitRuleData.ruleName }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.splitRule.merchantNo')">
          {{ splitRuleData.merchantNo }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.splitRule.ruleType')">
          <el-tag :type="getRuleTypeTagType(splitRuleData.ruleType)">
            {{ ruleTypeOptions[splitRuleData.ruleType] }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.splitRule.splitRatio')" v-if="splitRuleData.ruleType === SplitRuleTypeEnum.RATIO">
          {{ splitRuleData.splitRatio }}%
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.splitRule.splitAmount')" v-if="splitRuleData.ruleType === SplitRuleTypeEnum.AMOUNT">
          ¥{{ (splitRuleData.splitAmount / 100).toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.common.status')">
          <el-tag :type="getStatusTagType(splitRuleData.status)">
            {{ statusOptions[splitRuleData.status] }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 搜索表单 -->
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
        label-width="80px"
        class="mb-20px"
      >
        <el-form-item :label="t('settle.splitRecord.orderNo')" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            :placeholder="t('settle.common.pleaseInput') + t('settle.splitRecord.orderNo')"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item :label="t('settle.splitRecord.splitStatus')" prop="splitStatus">
          <el-select
            v-model="queryParams.splitStatus"
            :placeholder="t('settle.common.pleaseSelect') + t('settle.splitRecord.splitStatus')"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(label, value) in splitStatusOptions"
              :key="value"
              :label="label"
              :value="parseInt(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('settle.splitRecord.splitTime')" prop="splitTime">
          <el-date-picker
            v-model="queryParams.splitTime"
            type="datetimerange"
            range-separator="-"
            :start-placeholder="t('settle.common.startTime')"
            :end-placeholder="t('settle.common.endTime')"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            {{ t('settle.common.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            {{ t('settle.common.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 记录列表 -->
      <el-table :data="recordList" row-key="id" border>
        <el-table-column :label="t('settle.splitRecord.orderNo')" align="center" prop="orderNo" width="180" />
        <el-table-column :label="t('settle.splitRecord.totalAmount')" align="center" prop="totalAmount" width="120">
          <template #default="scope">
            ¥{{ (scope.row.totalAmount / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('settle.splitRecord.splitAmount')" align="center" prop="splitAmount" width="120">
          <template #default="scope">
            ¥{{ (scope.row.splitAmount / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('settle.splitRecord.receiverAccount')" align="center" prop="receiverAccount" width="150" />
        <el-table-column :label="t('settle.splitRecord.receiverName')" align="center" prop="receiverName" width="120" />
        <el-table-column :label="t('settle.splitRecord.splitStatus')" align="center" prop="splitStatus" width="100">
          <template #default="scope">
            <el-tag :type="getSplitStatusTagType(scope.row.splitStatus)">
              {{ splitStatusOptions[scope.row.splitStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('settle.splitRecord.splitTime')"
          align="center"
          prop="splitTime"
          width="180"
          :formatter="dateFormatter"
        />
        <el-table-column :label="t('settle.splitRecord.failReason')" align="center" prop="failReason" min-width="150">
          <template #default="scope">
            <span v-if="scope.row.failReason">{{ scope.row.failReason }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <Pagination
        :total="recordTotal"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getRecordList"
        class="mt-20px"
      />
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { getSplitRecordPageApi } from '@/api/settle/splitRule'
import type { SplitRuleVO, SplitRecordVO, SplitRecordPageReqVO } from '@/api/settle/types'
import { SplitRuleTypeEnum, SplitRuleStatusEnum, SplitStatusEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'

defineOptions({ name: 'SplitRecordList' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loading = ref(false)

// 分账规则数据
const splitRuleData = ref<SplitRuleVO>()

// 记录列表数据
const recordList = ref<SplitRecordVO[]>([])
const recordTotal = ref(0)

// 查询参数
const queryParams = reactive<SplitRecordPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  ruleId: undefined,
  orderNo: undefined,
  splitStatus: undefined,
  splitTime: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()

// 选项数据
const ruleTypeOptions = {
  [SplitRuleTypeEnum.RATIO]: t('settle.splitRule.ruleTypes.ratio'),
  [SplitRuleTypeEnum.AMOUNT]: t('settle.splitRule.ruleTypes.amount')
}

const statusOptions = {
  [SplitRuleStatusEnum.ENABLED]: t('settle.splitRule.statuses.enabled'),
  [SplitRuleStatusEnum.DISABLED]: t('settle.splitRule.statuses.disabled')
}

const splitStatusOptions = {
  [SplitStatusEnum.PENDING]: t('settle.splitRecord.splitStatuses.pending'),
  [SplitStatusEnum.SUCCESS]: t('settle.splitRecord.splitStatuses.success'),
  [SplitStatusEnum.FAILED]: t('settle.splitRecord.splitStatuses.failed')
}

/**
 * 打开对话框
 */
const open = (splitRule: SplitRuleVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('settle.splitRule.viewRecords') + ' - ' + splitRule.ruleName
  splitRuleData.value = splitRule
  
  // 重置查询参数
  resetQuery()
  queryParams.ruleId = splitRule.id
  
  // 获取记录列表
  getRecordList()
}

/**
 * 查询记录列表
 */
const getRecordList = async () => {
  loading.value = true
  try {
    const data = await getSplitRecordPageApi(queryParams)
    recordList.value = data.list
    recordTotal.value = data.total
  } catch (error) {
    console.error('查询分账记录列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getRecordList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  queryParams.orderNo = undefined
  queryParams.splitStatus = undefined
  queryParams.splitTime = undefined
}

// 标签类型获取函数
const getRuleTypeTagType = (type: number) => {
  const typeMap = {
    [SplitRuleTypeEnum.RATIO]: 'primary',
    [SplitRuleTypeEnum.AMOUNT]: 'success'
  }
  return typeMap[type] || ''
}

const getStatusTagType = (status: number) => {
  const statusMap = {
    [SplitRuleStatusEnum.ENABLED]: 'success',
    [SplitRuleStatusEnum.DISABLED]: 'info'
  }
  return statusMap[status] || ''
}

const getSplitStatusTagType = (status: number) => {
  const statusMap = {
    [SplitStatusEnum.PENDING]: 'warning',
    [SplitStatusEnum.SUCCESS]: 'success',
    [SplitStatusEnum.FAILED]: 'danger'
  }
  return statusMap[status] || ''
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.mt-20px {
  margin-top: 20px;
}
</style>
